window.onload = function (){
    fullTable(bkList);
}

function fullTable(array){
    let str ="";
    array.forEach(n =>{

        str += `<tr><td><img style="width: 40px;height: 40px" src=${n.img}></td><td>${n.name}</td>
                        <td>${n.author}</td><td>${n.price}</td>
                        <td><input type="button" value="查看" onclick="findById(${n.code})">
                       <input type="button" value="加入购物车" onclick="addBook(${n.code})"></td></tr>`;
    });

    $("data").innerHTML=str;
}

function fullTables(array){
    let str ="";
    let sum = 0;
    array.forEach(n =>{
        sum=sum+n.total;
        str += `<tr><td>${n.name}</td>
                        <td>${n.price}</td>
                        <td><input type="text" id="num${n.code}" value="${n.number}" onblur="changeNum(${n.code})"></td>
                        <td>${n.price * n.number}</td>
                        <td><input type="button" value="移除商品" onclick="del(${n.code})">
                      </td></tr>`;

    });

    $("datas").innerHTML=str;
    $("sumPrice").innerHTML="最终价为："+sum;
}


/**
 * 按ID得到对象
 * @param id
 * @returns {HTMLElement}
 */
function $(id) {
    return document.getElementById(id)
}

/**
 * 按书名查找书籍
 */
function findByName(){
    //得到文本框内容
    var nameStr = $("nameTxt").value;
    if ($("nameTxt").value==""){
        fullTable(bkList);
    }
    var newList = bkList.filter(n => n.name.indexOf(nameStr)!=-1);
    fullTable(newList);
}

function findById(code){

    var bkObj = bkList.find(n=> n.code==code);
    //将书本信息赋值给网页元素
    $("nameSpan").innerHTML=bkObj.name;
    $("authorSpan").innerHTML=bkObj.author;
    $("timeSpan").innerHTML=bkObj.time;
    $("priceSpan").innerHTML=bkObj.price;
    $("imgSpan").src=bkObj.img;
    $("findDiv").style.visibility="visible";
}

function addBook(code){
    var bkObj = bkList.find(n=> n.code==code);

    if (carList.find(e => e.code == code)){

        bkObj.number++;
    }else {
        bkObj.number=1;
        carList.push(bkObj)
    }
    bkObj.total=bkObj.price*bkObj.number;

}
function findCarInfo(){
    fullTables(carList);
    // $("carDiv").style.visibility="visible";
    $("contentDiv").style.visibility="visible";
}

function del(code){

    let index = carList.findIndex(n => n.code==code)
    carList.splice(index,1);
    fullTables(carList);
}

function changeNum(code){
    var bkObj = carList.find(n =>n.code==code);
    bkObj.number=parseInt($("num"+code).value);
    bkObj.total=parseInt($("num"+code).value) * bkObj.price;
    fullTables(carList);
}

function hiddena(){
    $("contentDiv").style.visibility="hidden";
}